#include "StdAfx.h"
#include "DownloadThread.h"
#include "UTL_STRNUM.h"

CDownloadThread::CDownloadThread(TASKTYPE nTaskType,CStdString strSource,CStdString strDestination):
m_strSourcePath(strSource),m_strDestinationPath(strDestination),m_nTaskType(nTaskType),m_pWinNetHttp(NULL)
{
}

CDownloadThread::~CDownloadThread(void)
{
	Cancel();
}

void CDownloadThread::Start(IWinNetEvent* pCallBack)
{
	_ASSERT(pCallBack);
	m_pCallBack = pCallBack;
	//if(CheckFileExist(m_strDestinationPath,FALSE) == FALSE)
	//{
	Create(TRUE);	
	//}
}

void CDownloadThread::Cancel()
{
	if(m_pWinNetHttp)
		m_pWinNetHttp->Abort();
	DestroyThread();
}

BOOL CDownloadThread::CheckFileExist(LPCTSTR pstrFileName, BOOL bCanZero)
{
	BOOL Result = FALSE;
	WIN32_FIND_DATA FileData={0}; 
	HANDLE hSearch;
	hSearch = FindFirstFile(pstrFileName, &FileData); 
	if (hSearch != INVALID_HANDLE_VALUE) 
	{ 
		if (bCanZero || FileData.nFileSizeLow || FileData.nFileSizeHigh)
			Result = TRUE;
	}

	FindClose(hSearch);
	return Result;
}

UINT __stdcall CDownloadThread::DefThreadProc()
{
	m_pWinNetHttp = new CWinNetHttp;
	m_pWinNetHttp->SetCallbackPoint(m_pCallBack);
	HRESULT hr = E_FAIL;
	if(TRUE == CheckFileExist(m_strDestinationPath,FALSE))
	{
		HRESULT hRes = m_pWinNetHttp->ResumeDown(m_strSourcePath,m_strDestinationPath);
		if(hRes == E_OVERFLOW)
			hr = S_OK;
		else 
			hr = hRes;
	}
	else
		hr = m_pWinNetHttp->DownLoadFile(m_strSourcePath,m_strDestinationPath,NULL);
	delete m_pWinNetHttp;
	m_pWinNetHttp = NULL;
	if( m_pCallBack)
	{
		m_pCallBack->OnDownloadComplete(hr == S_OK);
		
	}
	OutputDebugString(L"\nCDownloadThread DefThreadProc\n");
	return 0;
}
